import json

from django.db.models import F,Q
from django.shortcuts import render
from django.core.paginator import Paginator
from django import http
# Create your views here.
from django.views import View
from . import models
import logging,random
from .models import News
from dj31.utils.response import res_json,Code

logger = logging.getLogger('django')

# 首页
def index(request):
    title = '主页'
    tag = models.Tag.objects.filter(is_delete=False).only('name')  #获取数据
    return render(request,'news/毕业.html',context={'title':title,'tags':tag})

#新首页
def indexs(request):
    # print(request.get_full_path()) #获取带参数URL
    title = '主页'
    tag = models.Tag.objects.filter(is_delete=False).only('name')  #获取tag标签数据
    hot = models.HotNew.objects.only('news__image_url','news__title').select_related('news').filter(is_delete=False).order_by('priority')[0:3] #热门内容
    news_click = models.News.objects.only('title','image_url','update_time','tag__name','author__username').select_related('tag','author').order_by('-clicks')[0:2] #热门点击量数据

    return render(request,'news/index.html',context={'title':title,'tags':tag,'click':news_click,'hot':hot})

#加载更多
class NewsListView(View):
    def get(self,request):
        '''
        router :/news/
        tag_id
        page

        :param request:
        :return:
        '''
        try:
            tag= int(request.GET.get('tag_id',0))  #取不到，默认0
        except Exception as e:
            logging.error('标签错误{}'.format(e))
            tag = 0
        try:
            page = int(request.GET.get('page'))
        except Exception as e:
            logging.error('页码错误{}'.format(e))
            page = 1

        news_list = News.objects.values('title','digest','image_url','update_time','id').annotate(tag_name = F('tag__name'),author = F('author__username'))  #用values关联查询

        news_info = news_list.filter(is_delete=False,tag_id=tag) or news_list.filter(is_delete=False)

        #分页
        pages = Paginator(news_info,2) #一页几条
        try:
            news = pages.page(page)
        except Exception as e:
            logging.error(e)
            news = pages.page(pages.num_pages)
        data = {
                'news':list(news),
                'total_pages': pages.num_pages
            }
        return res_json(data=data)

#跳转评论界面，以及加载数据
class NewDetail(View):
    def get(self,request,news_id):
        news = News.objects.select_related('author','tag').only('author__username','tag__name','title','update_time','content').filter(is_delete=False,id=news_id).first() #优化查询，返回当前对象
        models.News.in_clicks(news) #调用函数进行增加访问量
        comm = models.Coment.objects.only('content','author__username','update_time').select_related('author').filter(is_delete=False,news_id=news_id) # 评论id

        comm_info = []
        for i in comm:
            comm_info.append(i.to_dict())



        news_clicks = models.News.objects.select_related('tag', 'author').order_by('id').filter(Q(id=random.randint(1,391))|Q(id=random.randint(392,782))|Q(id=random.randint(783,1173)))  #随机3个
        # print(news_clicks)
        if news:
            return render(request,'news/news_detail.html',context={'title':news,'news':news,'click':news_clicks,'comm':comm_info})
        else:
            return http.Http404('PAGE NOT FOUND')


#轮播图
class BannerView(View):
    def get(self,request):
        banner = models.Banner.objects.select_related('news').only('image_url','news__title').filter(is_delete=False).order_by('priority')#order_by排序

        b_info= []
        for i in banner:   #遍历取值
            b_info.append({
                'image_url':i.image_url,
                'news_id':i.id,
                'news_title':i.news.title,
            })

        data = {
            'banner':b_info
        }
        return res_json(data=data)

#评论
class Comment(View):
    def post(self,request,news_id):
        if not request.user.is_authenticated:
            return res_json(errno=Code.SESSIONERR,errmsg='用户未登陆')
        if not models.News.objects.filter(is_delete=False,id=news_id).exists():  #判断id是否存在，返回布尔值
            return res_json(errno=Code.PARAMERR,errmsg='参数错误')
        #获取参数

        js_data=request.body
        if not js_data:
            return res_json(errno=Code.PARAMERR,errmsg='参数错误')
        dict_data = json.loads(js_data)

        content = dict_data.get('content')
        if not dict_data['content']:
            return res_json(errno=Code.PARAMERR, errmsg='参数错误')
        #回复评论
        parent_id = dict_data.get('parent_id')
        if parent_id:
            if not models.Coment.objects.filter(is_delete=False,news_id=news_id,id=parent_id).exists():
                return res_json(errno=Code.PARAMERR, errmsg='副评论不存在')

        #保存在数据库
        news = models.Coment()
        news.content = content
        news.news_id = news_id
        news.author = request.user
        news.parent_id = parent_id if parent_id else None  #子评论  有则保存，无则为空
        news.save()  #保存



        return res_json(data=news.to_dict())

#搜索
class Search(View):
    def post(self,request,new_id):
        pass
#在线视频

#docker

#CRM系统

